/*
 * Copyright(c)2018,2024,guowenmeng24@163.comAllrightsreserved.
 */
package com.bkhech.aop;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;

/**
 * ServiceLogAspect
 *
 * @author guowm
 * @date 2024/11/06
 */
@EnableAspectJAutoProxy(exposeProxy = true)
@Component
@Aspect
@Slf4j
public class ServiceLogAspect {

    @Around("execution(* com.bkhech.service..*.*(..))")
    public Object recordTimeLog(ProceedingJoinPoint joinPoint) throws Throwable {
        // 统计每一个 service 实现的执行时间，如果执行时间太久，则进行 error 级别的日志输出
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        final Object proceed = joinPoint.proceed();
        stopWatch.stop();
        String pointName = joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName();
        final long totalTimeMillis = stopWatch.getTotalTimeMillis();
        if (totalTimeMillis > 2000) {
            log.error("执行业务: {}, 耗时: {}ms", pointName, totalTimeMillis);
        } else {
            log.info("执行业务: {}, 耗时: {}ms", pointName, totalTimeMillis);
        }
        return proceed;
    }

}